package com.example.demo;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.scp.client.ScpClient;
import org.apache.sshd.scp.client.ScpClientCreator;

/**
 * @ClassName scp
 * @Description
 * @date 2023/2/23 15:38
 * @Author yanceysong
 * @Version 1.0
 */
public class scp {
    //    private static String host = "192.168.67.48";
    private static final String host = "192.168.67.39";
    //    private static String host = "192.168.71.29";
    private static final String username = "root";
    private static final String password = "password";
    private static final Integer port = 22;

    //    private static String local = "F:\\miracle\\*";
    private static final String local = "/home/miracle/*";
    private static final String remote = "/home/luna/";
//    private static String remote = "F:\\luna\\";

    public static void scpFile(String local, String remote) throws Exception {
        long startTime = System.currentTimeMillis();

        // 创建 SSH客户端
        SshClient client = SshClient.setUpDefaultClient();

        // 启动 SSH客户端
        client.start();
        // 通过主机IP、端口和用户名，连接主机，获取Session
        ClientSession session = client.connect(username, host, port).verify().getSession();
        // 给Session添加密码
        session.addPasswordIdentity(password);
        // 校验用户名和密码的有效性
        boolean isSuccess = session.auth().verify().isSuccess();

        // 认证成功
        if (isSuccess) {
            long middleTime = System.currentTimeMillis();
            System.out.println("Connect host cost time: " + (middleTime - startTime) / 1000.0 + "s.");

            ScpClientCreator creator = ScpClientCreator.instance();
            // 创建 SCP 客户端
            ScpClient scpClient = creator.createScpClient(session);


            // ScpClient.Option.Rlecursive：递归copy，可以将子文件夹和子文件遍历copy
            scpClient.upload(local, remote, ScpClient.Option.Recursive);

            // 释放 SCP客户端
            scpClient = null;

            // 关闭 Session
            if (session.isOpen()) {
                session.close();
            }

            // 关闭 SSH客户端
            if (client.isOpen()) {
                client.stop();
                client.close();
            }
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Total Cost time: " + (endTime - startTime) / 1000.0 + "s.");
    }

    public static void main(String[] args) throws Exception {
        scpFile(local, remote);
    }
}
